require 'fastlane/action'
require_relative '../helper/upload_oss_action_helper'
require "faraday"
require "faraday_middleware"

module Fastlane
  module Actions
    class UploadOssActionAction < Action
      def self.run(params)
        UI.message("The upload_oss_action plugin is working!")
        file_path = params[:file_path]
        version = params[:version]
        if file_path.nil?
          UI.user_error!("You have to provide a build file")
        end
        if(!file_path.include?'apk')
          UI.user_error!("请上传apk类型的文件")
        end
        if version.nil?
          UI.user_error!("请提供版本号")
        end


        # start upload
        conn_options = {
          request: {
            timeout: 1000,
            open_timeout: 300,
          },
        }

        api_host = "https://ytoss.yotaienergy.com"

        request_params = {
          autoLogin: true,
          password: "Yongtai666888##",
          username: "admin"
        }

        # 发送登录请求
        conn = Faraday.new(
          url: api_host,
          headers: {'Content-Type' => 'application/json'}
        )

        response = conn.post('/prod-api/auth/login') do |req|
          req.body = request_params.to_json
        end

        res = response.body
        info = JSON.parse(res)
        UI.message("登陆code #{info["code"]}")

        if info["code"] != 200
          UI.user_error!("Get token is failed, info: #{info}")
        end

        access_token = info["data"]["access_token"]

       
        # 发送上传请求
        upload_params = {
          "version" => version,
          "systemName" => '永泰运维app',
          "appType" => 1,
          "platform" => 0,
        }
        
        upload_client = Faraday.new(nil, conn_options) do |c|
          c.headers['Authorization'] = "Bearer #{access_token}"
          c.request :multipart
          c.request :url_encoded, content_type: "multipart/form-data"
          c.response :json, content_type: /\bjson$/
          c.adapter :net_http
         
        end

      
        upload_params["file"] = Faraday::UploadIO.new(file_path, 'application/vnd.android.package-archive')

        UI.message "Start upload #{file_path} to oss..."

        response = upload_client.post( "#{api_host}/prod-api/oss/version/insert",upload_params) 

        self.checkPublishStatus(response, api_host, access_token)


      end

      def self.description
        "上传apk到管理系统后台"
      end

      def self.authors
        ["yangni"]
      end

      def self.return_value
        # If your method provides a return value, you can describe here what it does
      end

      def self.details
        # Optional:
        ""
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :file_path,    
                                        description: "apk 所在的路径",
                                        optional: true,
                                        type: String,
                                        ),
          FastlaneCore::ConfigItem.new(key: :version,    
                                        description: "apk的版本号",
                                        optional: true,
                                        type: String,
                                        ),
                              
        ]
      end

      def self.is_supported?(platform)
        # Adjust this if your plugin only works for a particular platform (iOS vs. Android, for example)
        # See: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Platforms.md
        #
        [:ios, :mac, :android].include?(platform)
        true
      end

      private

      def self.checkPublishStatus(response, api_host, token)
    
        info = response.body
        code = info["code"]
        if code == 200
          UI.success "Upload success. #{info}."
         
        else
          UI.user_error!("Oss Plugin Published Error: #{info} ")
        end
      end
    end
  end
end
